/*
 * EDF.cpp
 *
 *  Created on: Dec 20, 2011
 *      Author: quotrader
 */

#include "EDF.h"

EDF::EDF() {
	this->name = "Earliest-Deadline-First";
}

void EDF::run(TaskMng *tMng) {
	Task *taskList=tMng->tasks;
	int nof=tMng->numTask;
	Task tmpTL[nof];
	int minDeadline = 0;
	int maxDeadline = 0;
	int minIndex = 0;

	// copy task list to temporary place and get longest deadline
	for (int i = 0; i < nof; i++) {
		tmpTL[i] = taskList[i];
		if (maxDeadline < tmpTL[i].period and !tmpTL[i].done)
			maxDeadline = tmpTL[i].period;
	}

	// order tasks and put them back to their original place
	for (int i = 0; i < nof; i++) {
		minDeadline = maxDeadline;
		for (int j = 0; j < nof; j++)
			if (minDeadline >= tmpTL[j].period && tmpTL[j].period != -1 && !tmpTL[j].done) {
				minDeadline = tmpTL[j].period;
				minIndex = j;
			}
		if (tmpTL[minIndex].period != -1)
			taskList[i] = tmpTL[minIndex];
		tmpTL[minIndex].period = -1;
	}
	tMng->changed=false;

}

int EDF::rePrioritize(TaskMng *tMng, int sp, int ip) {
	Task *taskList=tMng->tasks;
	int nof=tMng->numTask;
	Task tmpTL[nof];
	int minDeadline = 0;
	int maxDeadline = 0;
	int minIndex = 0;
	int newParam=0;
	int hptID=0;

	// copy task list to temporary place and get longest deadline
	for (int i = 0; i < nof; i++) {
		tmpTL[i] = taskList[i];
		if (maxDeadline < tmpTL[i].period and !tmpTL[i].done)
			maxDeadline = tmpTL[i].period;
	}

	// order tasks and put them back to their original place
	for (int i = 0; i < nof; i++) {
		minDeadline = maxDeadline;
		for (int j = 0; j < nof; j++)
			if (minDeadline >= tmpTL[j].period && tmpTL[j].period != -1 && !tmpTL[j].done) {
				minDeadline = tmpTL[j].period;
				minIndex = j;
			}
		if (tmpTL[minIndex].period != -1){
			if(i==0)hptID=tmpTL[minIndex].id;
			newParam=sp + ((tMng->numTask-i) * ip);
			if(pthread_setschedprio(tmpTL[minIndex].taskThread,newParam)!=0)cout<<"I can't modify priority";
		}
		tmpTL[minIndex].period = -1;
	}
	tMng->changed=false;
	return hptID;

}
